package com.example.pdfandword.word;


import com.example.pdfandword.controller.TableEntity;
import com.example.pdfandword.util.WordUtil;
import org.apache.commons.jexl3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.util.Assert;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;

public class Test {

	public static void main(String[] args) throws IOException {

//
////
////
////		// TODO Auto-generated method stub
//		String infilePath = "C://Users//erzho//Documents//muban.docx";
//		String outfilePath = "C://Users//erzho//Documents/";
//		String outfilePathPdf = "c://147147.PDF";
//		Map<String, Object> resultsLabel = new HashMap<String, Object>();
//
//		Map<String, String> data = new HashMap<String, String>();
//		data.put("htbh","HT23333333333");
//		data.put("sfzh","zwr");
//		data.put("yhnlx","两千五");
////		data.put("htyfdh","5656565656");
//		resultsLabel.put("String", data);
//		Map<String, Object> resultsTable = new HashMap<String, Object>();
//		resultsTable.put("header",);
//		resultsTable.put();
//		resultsTable.put();
//		resultsTable.put();
//
//		resultsLabel.put("Table", resultsTable);
//
//		File filein = new File(infilePath);
//		try{
//			String url = WordUtil.build(filein, data, outfilePath, "111", "222",".docx");
//
//			System.out.println(url);
//		}catch (Exception e){
//
//		}
//		List<TableEntity> list = new ArrayList<>();
//		String[] strs = new String[]{"序号","名称","审批人","审批时间"};
//		List<TableEntity> tlist = new ArrayList<>();
//		TableEntity tab1 = new TableEntity();
//		tab1.setQuery01(Integer.toString(1));
//		tab1.setQuery02("内容");
//		tab1.setQuery03("内容");
//		tab1.setQuery04("内容");
//		tab1.setQuery05("内容");
//		tlist.add(tab1);
//		TableEntity tab2 = new TableEntity();
//		tab2.setQuery01(Integer.toString(2));
//		tab2.setQuery02("内容2");
//		tab2.setQuery03("内容2");
//		tab2.setQuery04("内容2");
//		tab2.setQuery05("内容2");
//		tlist.add(tab2);
//
//		String inFilePath = "E:\\模板.docx";//文件路径
//		String outFilePath = "E:\\结果.docx";//输出的文件路径
//		WordTemplateUtilities.downloadWord(tlist,strs,inFilePath,outFilePath);
//		downloadWord(list,inFilePath,outFilePath);





	}

	private static void testw() {
		//模拟表格数据
		ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
		HashMap<String, String> temp = new HashMap<>(3);
		temp.put("sn","1");
		temp.put("name","征信审查");
		temp.put("spn","第一个人");
		temp.put("time","2020-10-12 9:56");
		temp.put("yj","没有意见");
		list.add(temp);
//		temp = new HashMap<>(3);
//		temp.put("sn","2");
//		temp.put("name","第二个人");
//		temp.put("age","24");
//		list.add(temp);
		HashMap<String, Object> map = new HashMap<>(4);
		map.put("personlist",list);
		//word模板相对路径、word生成路径、word生成的文件名称、数据源
		exportWord("E://aa.docx", "E:/", "生成文件.docx", map);

	}

	public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {
		Assert.notNull(templatePath, "模板路径不能为空");
		Assert.notNull(temDir, "临时文件路径不能为空");
		Assert.notNull(fileName, "导出文件名不能为空");
		Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
		if (!temDir.endsWith("/")) {
			temDir = temDir + File.separator;
		}
		File dir = new File(temDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		try {
			XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
			String tmpPath = temDir + fileName;
			FileOutputStream fos = new FileOutputStream(tmpPath);
			doc.write(fos);
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 动态替换docx 表格内容 并下载
	 */
	public static void downloadWord(List<TableEntity> list, String inFilePath, String outFilePath){


		//添加表格
		try {
			XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inFilePath));// 生成word文档并读取模板

			//换行
			XWPFParagraph paragraph2 = document.createParagraph();
			XWPFRun paragraphRun2 = paragraph2.createRun();
			paragraphRun2.setText("\r");

			//附表格
			XWPFTable ComTable = document.createTable();
			int siz = ComTable.getRows().size();
			//列宽自动分割
            /*CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
            comTableWidth.setType(STTblWidth.DXA);
            comTableWidth.setW(BigInteger.valueOf(9072));*/

			System.out.println("长度====" + siz);
			//表格第一行
			XWPFTableRow comTableRowOne = ComTable.getRow(0);
			// 表格标题内容的填充
			// 因为document.createTable() 创建表格后默认是一行一列，所以第一行第一列是直接comTableRowOne.getCell(0).setText("序号"); 赋值的。
			// 第一行的其他列需要创建后才能赋值 comTableRowOne.addNewTableCell().setText("作品类型");
			comTableRowOne.getCell(0).setText("序号");
			comTableRowOne.addNewTableCell().setText("名称");
			comTableRowOne.addNewTableCell().setText("审批人");
			comTableRowOne.addNewTableCell().setText("审批时间");
			comTableRowOne.addNewTableCell().setText("审批意见");


			// 表格标题剧中+单元格大小设置
			setCellWitchAndAlign(comTableRowOne.getCell(0),"700",STVerticalJc.CENTER,STJc.CENTER);
			setCellWitchAndAlign(comTableRowOne.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
			setCellWitchAndAlign(comTableRowOne.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
			setCellWitchAndAlign(comTableRowOne.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
			setCellWitchAndAlign(comTableRowOne.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
			XWPFTableRow comTableRow = null;
			// 生成表格内容
			// 根据上面的表格标题 确定列数，所以下面创建的是行数。
			// comTableRow.getCell(1).setText(user.getName()); 确定第几列 然后创建赋值
			// 注意：我这边是列数较少固定的，如果列数不固定可循环创建上面的列数
			for (int i=0;i < list.size();i++) {
				comTableRow = ComTable.createRow();

				// 表格内容的填充
				TableEntity tab = list.get(i);

				/*-------------------变量替换（get）------------------------*/
				comTableRow.getCell(0).setText(((Integer)(i+1)).toString());
				comTableRow.getCell(1).setText(tab.getQuery01());
				comTableRow.getCell(2).setText(tab.getQuery02());
				comTableRow.getCell(3).setText(tab.getQuery03());
				comTableRow.getCell(4).setText(tab.getQuery04());
				/*-------------------变量替换（get）------------------------*/


				// 表格内容剧中+单元格大小设置
				setCellWitchAndAlign(comTableRow.getCell(0),"700",STVerticalJc.CENTER,STJc.CENTER);
				setCellWitchAndAlign(comTableRow.getCell(1),"1500",STVerticalJc.CENTER,STJc.CENTER);
				setCellWitchAndAlign(comTableRow.getCell(2),"1500",STVerticalJc.CENTER,STJc.CENTER);
				setCellWitchAndAlign(comTableRow.getCell(3),"1500",STVerticalJc.CENTER,STJc.CENTER);
				setCellWitchAndAlign(comTableRow.getCell(4),"3400",STVerticalJc.CENTER,STJc.CENTER);
			}


			//输出word内容文件流，文件形式
			FileOutputStream fos = new FileOutputStream(outFilePath);
			document.write(fos);
			fos.flush();
			fos.close();

		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{

		}
	}


	// 给生成的表格设置样式
	private static void setCellWitchAndAlign(XWPFTableCell cell, String width, STVerticalJc.Enum typeEnum, STJc.Enum align){
		CTTc cttc = cell.getCTTc();
		CTTcPr ctPr = cttc.addNewTcPr();
		ctPr.addNewVAlign().setVal(typeEnum);
		cttc.getPList().get(0).addNewPPr().addNewJc().setVal(align);
		CTTblWidth ctTblWidth = (ctPr != null && ctPr.isSetTcW() && ctPr.getTcW()!=null &&ctPr.getTcW().getW()!=null) ? ctPr.getTcW(): ctPr.addNewTcW();
		if(StringUtils.isNotBlank(width)){
			ctTblWidth.setW(new BigInteger(width));
			ctTblWidth.setType(STTblWidth.DXA);

		}
	}



}
